import { Injectable, Logger, OnModuleInit } from '@nestjs/common';
import { PrismaClient, TaskPlatform } from 'src/prisma/client';
import { CreateGoodsDto } from 'src/goods/dto/create-goods.dto';
import { TaskWithPlatforms } from 'src/types';

@Injectable()
export class PrismaService extends PrismaClient implements OnModuleInit {
  async onModuleInit() {
    await this.$connect();
  }
  async test(): Promise<string> {
    return 'prisma sverice test';
  }
  async getTask(taskId: number): Promise<TaskWithPlatforms | null> {
    const t1 = await this.task.findUnique({
      where: { id: taskId },
      include: {
        TaskPlatform: { include: { platform: { include: { cookies: true } } } },
      },
    });
    if (!t1) {
      return null;
    }
    const task = {
      ...t1,
      platforms: t1?.TaskPlatform.map((tp) => tp.platform),
    } as any;
    // const task = await this.task.findFirst({
    //   where: {
    //     id: taskId,
    //   },
    //   include: {
    //     platforms: { include: { cookies: true } },
    //   },
    // });
    delete task?.TaskPlatform;
    console.log(task);
    return task;
  }
  async deleteTask(taskId: number) {
    try {
      const deletedTask = await this.$transaction(async (prisma) => {
        // 1. Delete TaskPlatform relationships (junction table)
        await prisma.taskPlatform.deleteMany({
          where: {
            taskId: taskId,
          },
        });

        // 2. Delete associated Goods
        await prisma.goods.deleteMany({
          where: {
            taskId: taskId,
          },
        });

        // 3. Delete the Task itself
        const task = await prisma.task.delete({
          where: {
            id: taskId,
          },
        });

        return task;
      });

      return {
        success: true,
        message: `Task ${taskId} deleted successfully`,
        data: deletedTask,
      };
    } catch (error) {
      console.error('Error deleting task:', error);
      return {
        success: false,
        message: `Failed to delete task ${taskId}: ${error.message}`,
      };
    }
  }

  async storeGoods(data: CreateGoodsDto[]) {
    try {
      await this.goods.createMany({ data: data });
      Logger.warn(`successful stored ${data.length} goods`);
      return true;
    } catch (err) {
      Logger.error(err);
      return false;
    }
  }
}
